#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author:Zx
@file: comments.py
@time: 2025/7/23  10:45
# @describe: 评论
"""
import os

from flask import Blueprint, request, redirect, url_for, flash, jsonify, current_app, render_template
from flask_login import login_required, current_user
from werkzeug.utils import secure_filename

from utils.data_utils import load_data, save_data
import logging
from datetime import datetime

comments_bp = Blueprint('comments', __name__)


@comments_bp.route('/hike/<int:hike_id>/comment', methods=['POST'])
@login_required
def add_comment(hike_id):
    try:
        content = request.form.get('content')

        if not content:
            flash('评论内容不能为空', 'error')
            return redirect(url_for('hikes.hike_detail', hike_id=hike_id))

        # 根据用户角色设置评论状态
        comment_status = "approved" if current_user.role == "admin" else "pending"
        status_message = "评论已发布" if current_user.role == "admin" else "评论已提交，等待管理员审核"

        comments = load_data('comments.json')
        new_id = max([c.get('id', 0) for c in comments], default=0) + 1

        new_comment = {
            "id": new_id,
            "hike_id": hike_id,
            "user": current_user.username,
            "content": content,
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M"),
            "status": comment_status  # 根据用户角色设置状态
        }

        comments = load_data('comments.json')
        comments.append(new_comment)
        save_data(comments, 'comments.json')

        flash(status_message, 'success')
        return redirect(url_for('hikes.hike_detail', hike_id=hike_id))
    except Exception as e:
        logging.error(f'添加评论失败: {str(e)}', exc_info=True)
        flash('添加评论时发生错误', 'error')
        return redirect(url_for('hikes.hike_detail', hike_id=hike_id))


@comments_bp.route('/upload-image', methods=['POST'])
@login_required
def upload_image():
    """处理富文本编辑器图片上传"""
    if 'file' not in request.files:
        return jsonify({'error': '没有上传文件'}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': '没有选择文件'}), 400

    if file:
        # 创建上传目录
        upload_dir = os.path.join(current_app.config['IMAGES_UPLOAD_FOLDER'], 'comments')
        os.makedirs(upload_dir, exist_ok=True)

        # 安全处理文件名
        filename = secure_filename(file.filename)
        unique_filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{filename}"
        filepath = os.path.join(upload_dir, unique_filename)

        try:
            file.save(filepath)
            # 返回相对URL路径
            image_url = url_for('static', filename=f'uploads/comments/{unique_filename}')
            return {'link': image_url}
        except Exception as e:
            logging.error(f"评论图片上传失败: {e}")
            return {'error': '图片上传失败'}, 500


# 新增管理员审核路由
@comments_bp.route('/admin/comments', methods=['GET'])
@login_required
def manage_comments():
    if current_user.role != 'admin':
        flash('无权访问此页面', 'error')
        return redirect(url_for('main.index'))

    comments = load_data('comments.json')
    # 按时间倒序排序
    comments.sort(key=lambda x: x['timestamp'], reverse=True)
    return render_template('admin_comments.html', comments=comments)


@comments_bp.route('/admin/comment/<int:comment_id>/<action>', methods=['POST'])
@login_required
def review_comment(comment_id, action):
    print(f"收到请求 - 评论ID: {comment_id}, 操作: {action}")

    if current_user.role != 'admin':
        return jsonify({'success': False, 'message': '无权操作'}), 403

    comments = load_data('comments.json')
    comment = next((c for c in comments if c['id'] == comment_id), None)

    if not comment:
        print(f"未找到评论ID: {comment_id}")
        return jsonify({'success': False, 'message': '评论不存在'}), 404

    if action == 'approve':
        comment['status'] = 'approved'
    elif action == 'reject':
        comment['status'] = 'rejected'
    else:
        return jsonify({'success': False, 'message': '无效操作'}), 400

    save_data(comments, 'comments.json')
    return jsonify({'success': True})